package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.WxUser;
import com.ruoyi.system.mapper.WxUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class WeiXinDetailsServiceImpl implements AuthenticationProvider {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String code = ((WxAuthenticationToken) authentication).getCode();
        String openId = SecurityUtils.getOpenId(code);
        WxUser wxUser = wxUserMapper.selectAllByOpenid(openId);
        if (wxUser!=null){
            return createLoginUser(wxUser);
        }else {
            WxUser newWxUser = new WxUser();
            newWxUser.setOpenid(openId);
            newWxUser.setStatus("0");
            newWxUser.setWxPermission("wx");
            wxUserMapper.insert(newWxUser);
            return createLoginUser(newWxUser);
        }

    }

    public Authentication createLoginUser(WxUser wxUser)
    {
        Set<String> permissions = new HashSet<>();
        List<GrantedAuthority> authorities = new ArrayList<>();
        permissions.add(wxUser.getWxPermission());
        GrantedAuthority authority = new SimpleGrantedAuthority(wxUser.getWxPermission());
        authorities.add(authority);
        LoginUser loginUser = new LoginUser(wxUser.getWxUserId(), permissions);
        return new UsernamePasswordAuthenticationToken(loginUser,null,authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WxAuthenticationToken.class.isAssignableFrom(authentication);
    }


}
